<template>
  <div class="glass-system-page">
    <!-- Page Header -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-title">
          <div class="title-icon">
            <svg-icon icon-class="peoples" />
          </div>
          <div class="title-content">
            <h1>员工区域管理</h1>
            <p>Employee Region Management - 员工区域分配管理</p>
          </div>
        </div>
        <div class="header-actions">
          <button class="glass-button glass-button--primary" @click="handleAdd" v-hasPermi="['region:region_user:add']">
            <svg-icon icon-class="plus" />
            <span>新增分配</span>
          </button>
        </div>
      </div>
    </div>

    <!-- Search Form -->
    <div class="search-form" v-show="showSearch">
      <div class="glass-form">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item label="员工姓名" prop="userId">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入员工姓名"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="区域" prop="regionId">
            <el-tree-select 
              v-model="queryParams.region_id2" 
              :data="regionOptions" 
              :props="{ value: 'id', label: 'name', children: 'children' }" 
              value-key="id" 
              placeholder="请选择区域"  
              check-strictly 
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="部门" prop="deptId">
            <el-tree-select 
              v-model="queryParams.deptId" 
              :data="enabledDeptOptions" 
              :props="{ value: 'id', label: 'label', children: 'children' }" 
              value-key="id" 
              placeholder="请选择部门名称"  
              check-strictly 
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <button type="button" class="glass-button glass-button--primary" @click="handleQuery">
              <svg-icon icon-class="search" />
              <span>搜索</span>
            </button>
            <button type="button" class="glass-button" @click="resetQuery" style="margin-left: 8px;">
              <svg-icon icon-class="refresh" />
              <span>重置</span>
            </button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- Action Bar -->
    <div class="action-bar">
      <div class="action-content">
        <div class="action-buttons">
          <button class="glass-button glass-button--danger" :disabled="multiple" @click="handleDelete" v-hasPermi="['region:region_user:remove']">
            <svg-icon icon-class="delete" />
            <span>删除</span>
          </button>
          <button class="glass-button" @click="handleExport" v-hasPermi="['region:region_user:export']">
            <svg-icon icon-class="download" />
            <span>导出</span>
          </button>
        </div>
        <div class="action-tools">
          <div class="tool-item" @click="showSearch = !showSearch">
            <svg-icon icon-class="search" />
            <span>显示搜索</span>
          </div>
          <div class="tool-item" @click="getList">
            <svg-icon icon-class="refresh" />
            <span>刷新</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Data Table -->
    <div class="data-table">
      <div class="table-container">
        <el-table v-loading="loading" :data="region_userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="员工姓名" align="center" prop="userName" min-width="120">
            <template #default="scope">
              <div class="user-info centered-content">
                <svg-icon icon-class="user" class="user-icon" />
                <span class="user-name">{{ getUserNickName(scope.row.userId) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="部门" align="center" prop="deptName" min-width="150">
            <template #default="scope">
              <div class="dept-info centered-content">
                <svg-icon icon-class="tree" class="dept-icon" />
                <span class="dept-name">{{ getUserDeptName(scope.row.userId) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="区域" align="center" prop="regionName" min-width="200">
            <template #default="scope">
              <div class="region-info centered-content">
                <svg-icon icon-class="location" class="region-icon" />
                <span class="region-path">{{ scope.row.regionName || getRegionPath(scope.row.regionId) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template #default="scope">
              <div class="table-actions">
                <el-tooltip content="修改" placement="top">
                  <button class="action-btn action-btn--primary" @click="handleUpdate(scope.row)" v-hasPermi="['region:region_user:edit']">
                    <svg-icon icon-class="edit" />
                  </button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <button class="action-btn action-btn--danger" @click="handleDelete(scope.row)" v-hasPermi="['region:region_user:remove']">
                    <svg-icon icon-class="delete" />
                  </button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- Pagination -->
    <div class="pagination-container">
      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改员工区域管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="region_userRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="部门名称" prop="deptId">
          <el-tree-select v-model="form.deptId" :data="enabledDeptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属部门" check-strictly />
        </el-form-item>
        <el-form-item label="员工姓名" prop="userId">
          <el-tree-select v-model="form.userId" :data="userList.filter(edit=>edit.deptId==form.deptId)" :props="{ value: 'userId', label: 'nickName', children: 'children' }" value-key="id" placeholder="请选择员工" check-strictly />
        </el-form-item>
        <el-form-item label="员工id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入员工id" readonly/>
        </el-form-item>
        <el-form-item label="区域" prop="regionId">
          <el-tree-select v-model="form.regionId" :data="regionOptions" :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="请选择区域" :check-strictly="false" />
        </el-form-item>
        
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Region_user">
import { onMounted, onActivated } from "vue"
import { watch } from 'vue'
import { useRoute } from 'vue-router'
import { listRegion_user, getRegion_user, delRegion_user, addRegion_user, updateRegion_user } from "@/api/region/region_user"
import {deptTreeSelect} from "@/api/system/user"
import { listRegion } from "@/api/region/region"

import { listUser} from "@/api/system/user"
const { proxy } = getCurrentInstance()
const route = useRoute()
const regionList = ref([])
const userList = ref([])
const region_userList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const enabledDeptOptions = ref()
const deptOptions = ref()
const xg_or_xz  = ref(1)
const regionOptions = ref([])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    regionId: null,
    deptId:null,
    deptName: null,
    region_id2:null
  },
  rules: {
    userId: [
      { required: true, message: "员工信息不能为空", trigger: "blur" }
    ],
    regionId: [
      { required: true, message: "区域不能为空", trigger: "blur" }
    ],
    deptId: [
      { required: true, message: "部门名称不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询员工区域管理列表 */
function getList() {
  loading.value = true
  listRegion_user(queryParams.value).then(response => {
    region_userList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
  }).catch(error => {
    console.error('获取员工区域管理列表失败:', error)
    loading.value = false
  })
}

/** 查询员工列表 */
function getuserList() {
  loading.value = true
  // 获取完整的用户信息，包括部门信息
  listUser({ pageNum: 1, pageSize: 1000 }).then(res => {
    loading.value = false
    userList.value = res.rows ? res.rows.filter(edit=>edit.deptId==101 || edit.deptId==102) : []
  }).catch(error => {
    console.error('获取用户列表失败:', error)
    loading.value = false
  })
}

/** 查询区域信息管理列表 */
function getRegionList() {
  loading.value = true
  listRegion(queryParams.value).then(response => {
    regionList.value = proxy.handleTree(response.data, "id", "parentId")
    loading.value = false
  })
}
/** 查询区域信息管理下拉树结构 */
function getRegionTreeselect() {
  listRegion().then(response => {
    regionOptions.value=proxy.handleTree(response.data, "id", "parentId")
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    regionId: null,
    deptId: null
  }
  proxy.resetForm("region_userRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  loading.value = true
  
  // 获取所有员工区域数据
  listRegion_user(queryParams.value).then(response => {
    let filteredData = response.rows || []
    
    // 如果选择了区域，进行区域筛选（支持父子节点）
    if (queryParams.value.region_id2) {
      // 查找选中的区域节点
      const selectedRegion = findNodeById(regionList.value, queryParams.value.region_id2)
      
      if (selectedRegion) {
        // 获取该区域及其所有子区域的ID
        const regionIds = getAllChildRegionIds(selectedRegion)
        
        // 过滤出属于这些区域的员工
        filteredData = filteredData.filter(item => regionIds.includes(item.regionId))
      }
    }
    
    // 如果输入了员工姓名，进行姓名筛选
    if (queryParams.value.userName) {
      const keyword = queryParams.value.userName.trim().toLowerCase()
      // 在 userList 中查找匹配的 userIds
      const matchedUserIds = userList.value
        .filter(user => user.nickName && user.nickName.toLowerCase().includes(keyword))
        .map(user => user.userId)
      
      // 过滤出符合员工姓名的数据
      filteredData = filteredData.filter(item => matchedUserIds.includes(item.userId))
    }
    
    // 如果选择了部门，进行部门筛选
    if (queryParams.value.deptId) {
      const deptUserIds = userList.value
        .filter(user => user.deptId == queryParams.value.deptId)
        .map(user => user.userId)
      filteredData = filteredData.filter(item => deptUserIds.includes(item.userId))
    }
    
    // 更新表格数据
    region_userList.value = filteredData
    total.value = filteredData.length
    loading.value = false
  }).catch(error => {
    console.error('搜索失败:', error)
    loading.value = false
  })
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.region_id2 = null
  queryParams.value.userName = null
  queryParams.value.deptId = null
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  xg_or_xz.value = 0
  reset()
  open.value = true
  title.value = "添加员工区域管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  xg_or_xz.value = 1
  reset()
  const _id = row.id || ids.value
  getRegion_user(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改员工区域管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["region_userRef"].validate(valid => {
    if (valid) {
      if (xg_or_xz.value !=0) {
        updateRegion_user(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
          xg_or_xz.value = 1
        })
      } else {
        addRegion_user(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
          xg_or_xz.value = 1
        })
      }
      
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row ? row.id : ids.value
  proxy.$modal.confirm('是否确认删除员工区域管理编号为"' + _ids + '"的数据项？').then(function() {
    return delRegion_user(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('region/region_user/export', {
    ...queryParams.value
  }, `region_user_${new Date().getTime()}.xlsx`)
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
  })
}
function flattenRegionList(nodes) {
  let result = []
  nodes.forEach(node => {
    result.push(node)
    if (node.children && node.children.length > 0) {
      result = result.concat(flattenRegionList(node.children))
    }
  })
  return result
}
function getRegionName(id) {
  const flatRegions = flattenRegionList(regionList.value)
  return flatRegions.find(region => region.id == id)?.name || id
}

/** 获取完整的区域路径 */
function getRegionPath(regionId) {
  if (!regionId) return ''
  
  const flatRegions = flattenRegionList(regionList.value)
  const targetRegion = flatRegions.find(region => region.id == regionId)
  
  if (!targetRegion) return regionId
  
  // 构建路径数组
  const path = []
  let currentRegion = targetRegion
  
  // 向上遍历父节点
  while (currentRegion) {
    path.unshift(currentRegion.name) // 添加到数组开头
    if (currentRegion.parentId) {
      currentRegion = flatRegions.find(region => region.id == currentRegion.parentId)
    } else {
      break
    }
  }
  
  return path.join(' - ')
}

/** 获取用户昵称 */
function getUserNickName(userId) {
  if (!userId) return '未知用户'
  const user = userList.value.find(u => u.userId == userId)
  return user?.nickName || user?.userName || `用户${userId}`
}

/** 获取用户部门名称 */
function getUserDeptName(userId) {
  if (!userId) return '未知部门'
  const user = userList.value.find(u => u.userId == userId)
  return user?.dept?.deptName || user?.deptName || '未知部门'
}

/** 根据ID查找节点 */
function findNodeById(nodes, id) {
  if (!nodes || !id) return null
  for (const node of nodes) {
    if (node.id == id) return node
    if (node.children) {
      const found = findNodeById(node.children, id)
      if (found) return found
    }
  }
  return null
}

/** 获取所有子区域ID */
function getAllChildRegionIds(node) {
  let ids = [node.id]
  if (node.children) {
    node.children.forEach(child => {
      ids = ids.concat(getAllChildRegionIds(child))
    })
  }
  return ids
}
onMounted(() => {
  getDeptTree()
  getList()
  getuserList()
  getRegionList()
  getRegionTreeselect()
})

// 页面激活时刷新区域数据
onActivated(() => {
  getRegionTreeselect()
  getRegionList()
})

// 监听路由变化，刷新区域数据
watch(() => route.path, (newPath, oldPath) => {
  if (newPath === '/region/region_user' && oldPath && oldPath !== newPath) {
    getRegionTreeselect()
    getRegionList()
  }
})

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if(dept.id!=101 && dept.id!=102){
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}
// 监听 form.deptId 变化
watch(
  () => form.value.deptId,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      let userregionId=form.value.id
      if(xg_or_xz.value>=1 && xg_or_xz.value<3){
        xg_or_xz.value=xg_or_xz.value+1
      }else{
        reset()
        if(xg_or_xz.value>=3){
          form.value.id=userregionId
        }
        form.value.deptId=newVal
      }
      
    }
  }
)


</script>

<style scoped lang="scss">
@import '@/assets/styles/system-pages.scss';

// Employee region specific styles
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .user-icon {
    font-size: 16px;
    color: var(--accent-primary);
  }
  
  .user-name {
    font-weight: 500;
    color: var(--text-primary);
  }
}

.dept-info {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .dept-icon {
    font-size: 16px;
    color: var(--accent-secondary);
  }
  
  .dept-name {
    font-weight: 500;
    color: var(--text-primary);
  }
}

.region-info {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .region-icon {
    font-size: 16px;
    color: var(--accent-blue);
  }
  
  .region-name, .region-path {
    font-weight: 500;
    color: var(--text-primary);
    background: rgba(122, 156, 198, 0.1);
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
  }
}

// 居中显示内容
.centered-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
</style>
